package zts.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
public class CasController {

    @Value("${cas.server-url-prefix:}")
    private String casServerUrl;

    @GetMapping("/test")
    @ResponseBody
    public String test(HttpServletRequest request) {
        return request.getRemoteUser();
    }

    @GetMapping("/login")
    public void login(HttpServletRequest request, HttpServletResponse response, @RequestParam String url) throws IOException {
        ResponseCookie cookie = ResponseCookie.from("JSESSIONID", request.getSession().getId())
                .domain(request.getRemoteHost())
                .build();
        response.setHeader(HttpHeaders.SET_COOKIE, cookie.toString());
        response.sendRedirect(url);
    }

    @GetMapping("/logout")
    public void logout(HttpSession session, HttpServletResponse response, @RequestParam(required = false) String url) throws IOException {
        session.invalidate();
        response.sendRedirect(String.format("%s/logout?service=%s", casServerUrl, url));
    }
}
